package com.linxin.ai_automates_periodontal_treatment_system.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.log.Log;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.linxin.ai_automates_periodontal_treatment_system.common.Result;
import com.linxin.ai_automates_periodontal_treatment_system.entity.*;
import com.linxin.ai_automates_periodontal_treatment_system.service.*;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.*;

@Slf4j
@RestController
@RequestMapping("/designPlan")
public class DesignPlanController {
    @Value("${image.patient-imageCheck-path}")
    private String patientImageCheckPath;
    @Value("${image.patient-mouthImage-path}")
    private String patientMouthImagePath;

    @Autowired
    private DiagnosticRecordService diagnosticRecordService;
    @Autowired
    private SystemicDiseaseRecordService systemicDiseaseRecordService;
    @Autowired
    private DiseaseHistoryService diseaseHistoryService;
    @Autowired
    private TreatmentPlanService treatmentPlanService;
    @Autowired
    private PatientService patientService;

    /**
     * 获取指定病人的诊断记录
     *
     * @param requestMap
     * @param request
     * @return
     */
    @PostMapping("/getRecordInfo")
    public Result<List<DiagnosticRecord>> getDiagnosticRecord(@RequestBody Map<String, Object> requestMap, HttpServletRequest request) {
        // 获取病人id
        Integer patientId = (Integer) requestMap.get("patientId");
//        log.info("patientId: {}", patientId);
        // 获取医生id
        Integer doctorId = (Integer) request.getAttribute("doctorId");

        LambdaQueryWrapper<DiagnosticRecord> queryWrapper = new LambdaQueryWrapper<>();
        // 根据病人id和医生id查询诊断记录
        queryWrapper.eq(DiagnosticRecord::getPatientId, patientId).eq(DiagnosticRecord::getDoctorId, doctorId);

        // 在service中查询诊断记录, 返回集合
        List<DiagnosticRecord> diagnosticRecordList = diagnosticRecordService.list(queryWrapper);

        // 遍历集合, 在本地获取imageCheck
        for (DiagnosticRecord record : diagnosticRecordList) {
            // 获取这个记录的imageCheck
            String imageCheckName = record.getImageCheck();
            // 本地文件名
            String imageCheckPath = patientImageCheckPath + imageCheckName;
            if (FileUtil.exist(imageCheckPath) && !imageCheckName.isEmpty()) {
                // 头像文件存在，将头像文件内容转换为base64编码
                byte[] imageBytes = FileUtil.readBytes(imageCheckPath);
                String base64Image = Base64.getEncoder().encodeToString(imageBytes);
                // 添加data:image/png;base64,前缀
                base64Image = "data:image/png;base64," + base64Image;
                record.setImageCheck(base64Image);
            }
        }

        return Result.success(diagnosticRecordList);
    }

    /**
     * 获取 mouthImages
     *
     * @param requestMap
     * @return
     */
    @PostMapping("/getMouthImages")
    public Result<List<String>> getMouthImages(@RequestBody Map<String, Object> requestMap) {
        // 获取 recordId
        Integer recordId = (Integer) requestMap.get("recordId");
//        log.info("id: {}", recordId);
        // 根据 recordId 查询 DiagnosticRecord
        DiagnosticRecord record = diagnosticRecordService.getById(recordId);
        // 获取 mouthImages
        String mouthImagesNames = record.getMouthImages();
        // 在本地获取 mouthImages
        List<String> mouthImages = new ArrayList<>();
        if (mouthImagesNames != null && !mouthImagesNames.isEmpty()) {
            String[] mouthImageNames = mouthImagesNames.split(",");
            for (String mouthImageName : mouthImageNames) {
                String mouthImagePath = patientMouthImagePath + mouthImageName;
                if (FileUtil.exist(mouthImagePath) && !mouthImageName.isEmpty()) {
                    // 口内照片文件存在，将口内照片文件内容转换为base64编码
                    byte[] mouthImageBytes = FileUtil.readBytes(mouthImagePath);
                    String base64MouthImage = Base64.getEncoder().encodeToString(mouthImageBytes);
                    // 添加data:image/png;base64,前缀
                    base64MouthImage = "data:image/png;base64," + base64MouthImage;
                    mouthImages.add(base64MouthImage);
                }
            }
        }
        // 返回 mouthImages
        return Result.success(mouthImages);
    }


    /**
     * 删除诊断记录
     *
     * @param id
     * @return
     */
    @DeleteMapping("/delete/{id}")
    public Result<String> deleteDiagnosticRecord(@PathVariable("id") Integer id) {

        // 获取对于id的诊断记录
        DiagnosticRecord record = diagnosticRecordService.getById(id);

        // 根据 patientId 获取病人信息
        Patient patient = patientService.getById(record.getPatientId());
        // 将patient的诊断记录数-1
        patient.setRecordCount(patient.getRecordCount() - 1);
        patientService.updateById(patient);

        // 获取对应的mouthImages
        String mouthImages = record.getMouthImages();
        // 遍历mouthImages, 删除本地文件
        if (mouthImages != null && !mouthImages.isEmpty()) {
            String[] mouthImageNames = mouthImages.split(",");
            for (String mouthImageName : mouthImageNames) {
                String mouthImagePath = patientMouthImagePath + mouthImageName;
                if (FileUtil.exist(mouthImagePath) && !mouthImageName.isEmpty()) {
                    FileUtil.del(mouthImagePath);
                }
            }
        }
        // 获取对应的imageCheck
        String imageCheck = record.getImageCheck();
        // 删除本地文件
        if (imageCheck != null && !imageCheck.isEmpty()) {
            String imageCheckPath = patientImageCheckPath + imageCheck;
            if (FileUtil.exist(imageCheckPath) && !imageCheck.isEmpty()) {
                FileUtil.del(imageCheckPath);
            }
        }
        // 根据id删除对应的诊断记录
        diagnosticRecordService.removeById(id);
        // 根据id删除对应的疾病史
        diseaseHistoryService.remove(new LambdaQueryWrapper<DiseaseHistory>().eq(DiseaseHistory::getRecordId, id));
        // 根据id删除对应的全身状况表单
        systemicDiseaseRecordService.remove(new LambdaQueryWrapper<SystemicDiseaseRecord>().eq(SystemicDiseaseRecord::getRecordId, id));
        return Result.success("删除成功");
    }

    /**
     * 新增诊断记录, 疾病史, 全身状况表单, 口内照片, 影像学检查图片
     *
     * @param recordMap
     * @param request
     * @return
     */
    @PostMapping("/add")
    public Result<String> addDiagnosticRecord(@RequestBody Map<String, Object> recordMap, HttpServletRequest request) {
        // 从map中获取diagnosticRecord, diseaseHistory, systemicDiseaseRecord, treatmentPlan
        // diagnosticRecord
        Map<String, Object> diagnosticRecordMap = (Map<String, Object>) recordMap.get("diagnosticRecord");
        // 使用ObjectMapper将Map转换为DiagnosticRecord对象
        ObjectMapper objectMapper = new ObjectMapper();
        DiagnosticRecord record = objectMapper.convertValue(diagnosticRecordMap, DiagnosticRecord.class);

        // 获取口内照片集合
        List<String> mouthImages = (List<String>) recordMap.get("mouthImages");
        // 定义一个 sb 用于存储上传后的图片名称
        StringBuilder sb = new StringBuilder();
        // 判断 mouthImages 是否为空
        if (mouthImages == null || mouthImages.isEmpty()) {
            // 口内照片为空, 则不上传
            record.setMouthImages(null);
        } else {
            // 上传口内照片
            for (String mouthImage : mouthImages) {
                try {
                    // 移除可能的 data URI scheme 前缀
                    if (mouthImage.startsWith("data:image/png;base64,")) {
                        mouthImage = mouthImage.substring("data:image/png;base64,".length());
                    }
                    // 填充base64字符串长度为4的倍数
                    int padding = (4 - mouthImage.length() % 4) % 4;
                    mouthImage = mouthImage + "=".repeat(padding);
                    // 将base64编码的图片数据转换为字节数组
                    byte[] decodedMouthImage = Base64.getDecoder().decode(mouthImage);
                    // log.info("decodedMouthImage length: {}", decodedMouthImage.length);
                    String uniqueFileName = UUID.randomUUID().toString() + ".jpg";
                    // 保存口内照片到文件
                    FileUtil.writeBytes(decodedMouthImage, patientMouthImagePath + uniqueFileName);
                    // 保存图片名称到 sb
                    sb.append(uniqueFileName).append(",");
                } catch (IllegalArgumentException e) {
                    // log.error("Failed to decode base64 mouthImage: {}", e.getMessage());
                    Result.error("口内照片上传失败, 请检查图片格式");
                } catch (Exception e) {
                    // log.error("Failed to upload mouthImage: {}", e.getMessage());
                    Result.error("口内照片上传失败, 请检查服务器配置");
                }
            }
            // 更新 口内照片 名称
            record.setMouthImages(sb.toString());
        }

        // 上传影像学检查图片
        String imageCheck = record.getImageCheck();
        log.info("imageCheck: " + imageCheck);
        if (imageCheck != null && !imageCheck.isEmpty()) {
            try {
                // 移除可能的 data URI scheme 前缀
                if (imageCheck.startsWith("data:image/png;base64,")) {
                    imageCheck = imageCheck.substring("data:image/png;base64,".length());
                }

                // 填充base64字符串长度为4的倍数
                int padding = (4 - imageCheck.length() % 4) % 4;
                imageCheck = imageCheck + "=".repeat(padding);

                // 将base64编码的图片数据转换为字节数组
                byte[] decodedAvatar = Base64.getDecoder().decode(imageCheck);
                // log.info("decodedAvatar length: {}", decodedAvatar.length);

                String uniqueFileName = UUID.randomUUID().toString() + ".jpg";
                // 保存头像图片到文件
                FileUtil.writeBytes(decodedAvatar, patientImageCheckPath + uniqueFileName);

                record.setImageCheck(uniqueFileName);

            } catch (IllegalArgumentException e) {
                // log.error("Failed to decode base64 avatar: {}", e.getMessage());
                Result.error("头像上传失败, 请检查图片格式");
            } catch (Exception e) {
                // log.error("Failed to upload avatar: {}", e.getMessage());
                Result.error("头像上传失败, 请检查服务器配置");
            }
        }

        // diseaseHistory
        Map<String, Object> diseaseHistoryMap = (Map<String, Object>) recordMap.get("diseaseHistory");
        DiseaseHistory diseaseHistory = objectMapper.convertValue(diseaseHistoryMap, DiseaseHistory.class);


        // systemicDiseaseRecord
        Map<String, Object> systemicDiseaseRecordMap = (Map<String, Object>) recordMap.get("systemicDiseaseRecord");
        SystemicDiseaseRecord systemicDiseaseRecord = objectMapper.convertValue(systemicDiseaseRecordMap, SystemicDiseaseRecord.class);

        // treatmentPlan
        Map<String, Object> treatmentPlanMap = (Map<String, Object>) recordMap.get("treatmentPlan");
        TreatmentPlan treatmentPlan = objectMapper.convertValue(treatmentPlanMap, TreatmentPlan.class);

        // 获取医生id
        Integer doctorId = (Integer) request.getAttribute("doctorId");

        // 给诊断记录对象设置医生id
        record.setDoctorId(doctorId);
        // 设置创建时间
        record.setCreateTime(LocalDateTime.now());
        // 设置更新时间
        record.setUpdateTime(LocalDateTime.now());
        // 将诊断记录对象保存到数据库
        diagnosticRecordService.save(record);

        // 根据病人id和医生id获取最新的诊断记录
        LambdaQueryWrapper<DiagnosticRecord> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DiagnosticRecord::getPatientId, record.getPatientId()).eq(DiagnosticRecord::getDoctorId, doctorId);
        queryWrapper.orderByDesc(DiagnosticRecord::getCreateTime);
        // 获取集合
        List<DiagnosticRecord> diagnosticRecordList = diagnosticRecordService.list(queryWrapper);
        Integer recordId = diagnosticRecordList.get(0).getId();

        // 给疾病史对象设置病人id和诊断记录id
        diseaseHistory.setPatientId(record.getPatientId());
        diseaseHistory.setRecordId(recordId);
        // 设置创建时间
        diseaseHistory.setCreateTime(LocalDateTime.now());
        // 设置更新时间
        diseaseHistory.setUpdateTime(LocalDateTime.now());
        // 将疾病史对象保存到数据库
        diseaseHistoryService.save(diseaseHistory);

        // 获取 病人 信息
        Patient patient = patientService.getById(record.getPatientId());
        // 病人 诊断记录数 +1
        patient.setRecordCount(patient.getRecordCount() + 1);
        patientService.updateById(patient);

        // 判断 全身状况表单 是否为空
        if (systemicDiseaseRecordMap != null) {
            // 给全身状况表单对象设置病人id和诊断记录id
            // 给全身状况表单对象设置病人id和诊断记录id
            systemicDiseaseRecord.setPatientId(record.getPatientId());
            systemicDiseaseRecord.setRecordId(recordId);
            // 设置创建时间
            systemicDiseaseRecord.setCreateTime(LocalDateTime.now());
            // 设置更新时间
            systemicDiseaseRecord.setUpdateTime(LocalDateTime.now());
            // 将全身状况表单对象保存到数据库
            systemicDiseaseRecordService.save(systemicDiseaseRecord);
        } else{
            // 创建一个全身状况表单对象
            SystemicDiseaseRecord newSystemicDiseaseRecord = new SystemicDiseaseRecord();
            // 给全身状况表单对象设置病人id和诊断记录id
            newSystemicDiseaseRecord.setPatientId(record.getPatientId());
            newSystemicDiseaseRecord.setRecordId(recordId);
            // 设置创建时间
            newSystemicDiseaseRecord.setCreateTime(LocalDateTime.now());
            // 设置更新时间
            newSystemicDiseaseRecord.setUpdateTime(LocalDateTime.now());
            // 将全身状况表单对象保存到数据库
            systemicDiseaseRecordService.save(newSystemicDiseaseRecord);
        }

       // 将 治疗方案 保存到数据库
        treatmentPlan.setPatientId(record.getPatientId());
        treatmentPlan.setDiagnosticRecordId(recordId);
        treatmentPlan.setDoctorId(doctorId);
        treatmentPlan.setCreateTime(LocalDateTime.now());
        treatmentPlan.setUpdateTime(LocalDateTime.now());

        treatmentPlanService.save(treatmentPlan);

        return Result.success("新增成功");
    }


    /**
     * 编辑诊断记录
     *
     * @param recordMap
     * @param request
     * @return
     */
    @PutMapping("/editRecord")
    public Result<String> editDiagnosticRecord(@RequestBody Map<String, Object> recordMap, HttpServletRequest request) {
        // 获取诊断记录
        Map<String, Object> diagnosticRecordMap = (Map<String, Object>) recordMap.get("diagnosticRecord");
        ObjectMapper objectMapper = new ObjectMapper();
        DiagnosticRecord record = objectMapper.convertValue(diagnosticRecordMap, DiagnosticRecord.class);
//        log.info("编辑诊断记录: " + record.toString());

        // 获取口内照片集合
        List<String> mouthImages = (List<String>) recordMap.get("mouthImages");
//        log.info("mouthImages: " + mouthImages.toString());
        // 定义一个 sb 用于存储上传后的图片名称
        StringBuilder sb = new StringBuilder();
        // 判断 mouthImages 是否为空
        if (mouthImages == null || mouthImages.isEmpty()) {
            // 口内照片为空, 则不上传
            record.setMouthImages(null);
        } else {
            // 上传口内照片
            for (String mouthImage : mouthImages) {
                try {
                    // 移除可能的 data URI scheme 前缀
                    if (mouthImage.startsWith("data:image/png;base64,")) {
                        mouthImage = mouthImage.substring("data:image/png;base64,".length());
                    }
                    // 填充base64字符串长度为4的倍数
                    int padding = (4 - mouthImage.length() % 4) % 4;
                    mouthImage = mouthImage + "=".repeat(padding);
                    // 将base64编码的图片数据转换为字节数组
                    byte[] decodedMouthImage = Base64.getDecoder().decode(mouthImage);
                    // log.info("decodedMouthImage length: {}", decodedMouthImage.length);
                    String uniqueFileName = UUID.randomUUID().toString() + ".jpg";
                    // 保存口内照片到文件
                    FileUtil.writeBytes(decodedMouthImage, patientMouthImagePath + uniqueFileName);
                    // 保存图片名称到 sb
                    sb.append(uniqueFileName).append(",");
                } catch (IllegalArgumentException e) {
                    // log.error("Failed to decode base64 mouthImage: {}", e.getMessage());
                    Result.error("口内照片上传失败, 请检查图片格式");
                } catch (Exception e) {
                    // log.error("Failed to upload mouthImage: {}", e.getMessage());
                    Result.error("口内照片上传失败, 请检查服务器配置");
                }
            }
        }
        // 根据 recordId 查询 DiagnosticRecord
        DiagnosticRecord oldRecord1 = diagnosticRecordService.getById(record.getId());
        // 删除旧的口内照片
        String oldMouthImagesNames = oldRecord1.getMouthImages();
        // 内容为为 sb 字符串, 逗号分隔的图片名称
        if (oldMouthImagesNames != null && !oldMouthImagesNames.isEmpty()) {
            String[] oldMouthImageNames = oldMouthImagesNames.split(",");
            for (String oldMouthImageName : oldMouthImageNames) {
                String oldMouthImagePath = patientMouthImagePath + oldMouthImageName;
                if (FileUtil.exist(oldMouthImagePath)) {
                    FileUtil.del(oldMouthImagePath);
                }
            }
        }
        // 设置新的口内照片名称
        record.setMouthImages(sb.toString());


        // 获取影像学检查图片
        String imageCheck = record.getImageCheck();
//        log.info("imageCheck: " + imageCheck);

        // 根据 recordId 查询 DiagnosticRecord
        DiagnosticRecord oldRecord2 = diagnosticRecordService.getById(record.getId());
        // 删除旧的影像学检查图片
        String oldImageCheckName = oldRecord2.getImageCheck();
        if (oldImageCheckName != null && !oldImageCheckName.isEmpty()) {
            String oldImageCheckPath = patientImageCheckPath + oldImageCheckName;
            if (FileUtil.exist(oldImageCheckPath)) {
                FileUtil.del(oldImageCheckPath);
            }
        }
        // 上传影像学检查图片
        // 判断 imageCheck 是否为空
        if (imageCheck != null && !imageCheck.isEmpty()) {
            try {
                // 移除可能的 data URI scheme 前缀
                if (imageCheck.startsWith("data:image/png;base64,")) {
                    imageCheck = imageCheck.substring("data:image/png;base64,".length());
                }

                // 填充base64字符串长度为4的倍数
                int padding = (4 - imageCheck.length() % 4) % 4;
                imageCheck = imageCheck + "=".repeat(padding);

                // 将base64编码的图片数据转换为字节数组
                byte[] decodedAvatar = Base64.getDecoder().decode(imageCheck);
                // log.info("decodedAvatar length: {}", decodedAvatar.length);

                String uniqueFileName = UUID.randomUUID().toString() + ".jpg";
                // 保存头像图片到文件
                FileUtil.writeBytes(decodedAvatar, patientImageCheckPath + uniqueFileName);

                // 设置新的影像学检查图片名称
                record.setImageCheck(uniqueFileName);

            } catch (IllegalArgumentException e) {
                // log.error("Failed to decode base64 avatar: {}", e.getMessage());
                Result.error("影像学检查图片上传失败, 请检查图片格式");
            } catch (Exception e) {
                // log.error("Failed to upload avatar: {}", e.getMessage());
                Result.error("影像学检查图片上传失败, 请检查服务器配置");
            }
        }

        // 设置医生id
        Integer doctorId = (Integer) request.getAttribute("doctorId");
        record.setDoctorId(doctorId);
        // 设置更新时间
        record.setUpdateTime(LocalDateTime.now());
        // 更新诊断记录
        diagnosticRecordService.updateById(record);

        return Result.success("编辑成功");
    }

}
